package com.studydemo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studydemo.common.R;
import com.studydemo.entity.MyUserDetails;
import com.studydemo.entity.SysUser;
import com.studydemo.mapper.SysUserMapper;
import com.studydemo.service.SysUserService;
import com.studydemo.utils.JwtUtil;
import com.studydemo.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;


@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",username);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        //最后返回UserDetails对象
        return new MyUserDetails(user);
    }

    @Override
    public R loginIn(SysUser sysUser) {
        UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(sysUser.getPhone(),sysUser.getPassworde());
        String name = token.getName();
        String password=token.getCredentials().toString();
        MyUserDetails userDetails = (MyUserDetails) loadUserByUsername(name);
        if (!passwordEncoder.matches(password,userDetails.getPassword())){
            throw new RuntimeException("用户名或者密码错误了");
        }
        String jwt = JwtUtil.createJWT(name);
        RedisUtils.set("login:"+name,userDetails.getSysUser());
        HashMap<String,Object> map=new HashMap<>();
        map.put("token", jwt);
        return R.success(map, "登录成功");
    }
}
